import {createStore} from 'vuex'
import router from "../router";
import {genRoutes} from "../utils/router";

const store = createStore({
    state() {
        return {
            collapsed: false,
            isDrawer: false,
            device: '',
            routes: [],
            permiss: null,
            cacheView: []
        }
    },
    getters: {
        getCollapsed: (state) => state.collapsed,
        getRoutes: (state) => state.routes,
        getPermiss: (state) => state.permiss,
        getCacheView: (state) => state.cacheView
    },
    mutations: {
        TOGGLE_COLLAPSED: (state, payload) => {
            state.collapsed = payload
        },
        TOGGLE_DEVICE: (state, payload) => {
            state.device = payload
        },
        TOGGLE_DRAWER:(state, payload) =>{
            state.isDrawer = payload
        },
        /**
         * map存储菜单权限
         */
        SET_PAGE_PERMISSION: (state, payload) => {
            const permissMap = new Map()
            payload.forEach(item => {
                if (item.children && item.children.length && item.children[0].type === 2) {
                    permissMap.set(item.webUrl, item.children)
                }
            })
            state.permiss = permissMap
        },
        SET_ROUTES: (state, payload) => {
            state.routes = payload.sort((a, b) => a.meta.sortNum - b.meta.sortNum).map(item => {
                if (item.children && item.children.length) {
                    item.children.sort((a, b) => a.meta.sortNum - b.meta.sortNum)
                }
                return item
            })
        },
        CLEAR_CACHE: (state) => {
            state.routes.forEach(item => {
                if (item.name) {
                    router.removeRoute(item.name)
                }
            })
            Object.assign(state, {
                routes: [],
                menuList: [],
                cacheView: []
            })
        },
        CACHE_VIEW: (state, payload) => {
            state.cacheView.push(payload)
        },
        DEL_CACHE_VIEW: (state, payload) => {
            state.cacheView = payload
        }
    },
    actions: {
        change_Collapsed({commit}, payload) {
            commit('TOGGLE_COLLAPSED', payload)
        },
        convertRoutes({commit}, payload) {
            /**
             * permission  按钮权限
             * route 路由
             */
            const {permission, route} = genRoutes(payload)
            // 动态添加路由
            route.forEach(item => {
                router.addRoute(item)
            })
            commit('SET_PAGE_PERMISSION', permission)
            commit('SET_ROUTES', route[0].children)
        },
    }
})

export default store
